const Koa = require('koa')
const app = new Koa();
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const { koaBody } = require("koa-body")
const logger = require('koa-logger')
const cors = require('koa2-cors')
const fs = require("fs")
const path = require('path');
const jwt = require("koa-jwt");
const { secretKey } = require('./middlear/token')
const static = require('koa-static');
const { assetsDir } = require("./config")
const mount = require('koa-mount')
const { initBaseResource } = require('./config/init')
initBaseResource();
// error handler
onerror(app)

app.use(cors({
  origin: '*',//前端的地址
  credentials: true,//允许跨域带cookie
}))

app.use(koaBody({
  multipart: true,
  formidable: {
    maxFileSize: 1500 * 1024 * 1024 //文件上传大小限制 5M
  }
}))

app.use(bodyparser({
  enableTypes: ['json', 'form', 'text'],
  formLimit: "15mb",
  jsonLimit: "15mb"
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/views'))
app.use(static("/"), { defer: true })
// app.use(static(assetsDir))

//将静态资源目录挂载到 /bil_Ste_static
app.use(mount("/bil_Ste_static", static(assetsDir)))



app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


//对没有验签通过返回的错误进行拦截处理
app.use(async (ctx, next) => {
  const start = new Date()
  // 如果token没有经过验证中间件会返回401错误，可以通过下面的中间件自定义处理这个错误
  await next().catch((err) => {
    if (401 == err.status) {
      ctx.status = 401;
      ctx.body = '没有找到token信息，请检查接口请求头信息';
      console.log("未找到token: " + err);
      ctx.body = {
        status: "4001",
        message: "身份验证未通过"
      }
    } else {
      logger.error(err);
      throw err;
    }
  })
  const ms = new Date() - start
})

const unlessPath = [
  /^\/bil_Ste_static/,
  /^\/file_images/,
  /^\/auth\/login/,
  /^\/user\/add/,
  /^\/subject\/detail/,
  /^\/subject\/list/,
  /^\/home\/getMonication/,
  /^\/aliossdownload/,
  /^\/uvlog\/add/,
  /^\/uvlog\/list/,
  /^\/article\/list/,
  /^\/article\/detail/,
  /^\/message\/list/,
  /^\/message\/add/,
  /^\/ali-oss\/sts/,
  /^\/aliUpload/,
  /^\/index/,
]

// 登录接口不验证toekn '/api/login'
app.use(jwt({ secret: secretKey }).unless({ path: unlessPath }));

/**@description 递归创建路由 遍历判断是文件还是文件夹，自动创建 */
const createRoute = (directoryPath) => {
  // routes
  fs.readdirSync(directoryPath).forEach(file => {
    if (file.includes("config") || file.includes("zip") || file.includes("txt")) {
      return;
    }
    const fullPath = path.join(directoryPath, file);
    const stat = fs.statSync(fullPath);

    if (stat.isFile()) {
      let api = require(`${directoryPath}/${file}`)
      app.use(api.routes(), api.allowedMethods())
    } else if (stat.isDirectory()) {
      createRoute(`${directoryPath}/${file}`)
    }
  })
}

const rootPath = path.join(__dirname, "./routes");
createRoute(rootPath);

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
